package cas

import (
	"fmt"
	"math/rand"
	"sync"
	"sync/atomic"
	"time"
)

type Config struct {
	NodeName string
	Addr     string
	Count    int32
}

func loadNewConfig() Config {
	return Config{
		NodeName: "北京",
		Addr:     "10.77.95.27",
		Count:    rand.Int31(),
	}
}
func update_config() {
	var config atomic.Value
	config.Store(loadNewConfig())
	var cond = sync.NewCond(&sync.Mutex{})

	// 设置新的config
	go func() {
		for {
			time.Sleep(time.Duration(2) * time.Second)
			config.Store(loadNewConfig())
			cond.Broadcast() // 通知等待着配置已变更
		}
	}()

	go func() {
		for {
			cond.L.Lock()
			cond.Wait()                 // 等待变更信号
			c := config.Load().(Config) // 读取新的配置
			fmt.Printf("new config: %+v\n", c)
			cond.L.Unlock()
		}
	}()

	select {}
}

var (
	counter int32          //计数器
	wg      sync.WaitGroup //信号量
)

func handle(delta int) int32 {
	//1. 信号量
	wg.Add(delta)

	//2.开启协程
	for i := 0; i < delta; i++ {
		go incCounter()
	}

	//3.等待协程结束
	wg.Wait()
	return counter
}

func incCounter() {
	defer wg.Done()
	// 保证cas成功
	for {
		//2.1原子操作
		// 可能cas失败
		ok := atomic.CompareAndSwapInt32(&counter, counter, counter+1)
		if ok {
			// 并发读写时，读到已写完的数据
			//fmt.Printf("go routine:%d, spinnum:%d\n", goutil.GoID(), counter) //err
			return
		}
	}
}
